﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using MPCR.Client.Dialog;
using MPCR.Client.Hepler;
using MPCR.Client.TouchView.Home.Pages;
using MPCR.Client.TouchView.Keyboard;
using MPCR.Contracts.Entity;
using MPCR.Client.TouchView.UserContorl;
using MPCR.Client.Util;
using MPCR.Client.Custom;
using System.Windows.Media.Animation;

namespace MPCR.Client.TouchView.Home
{
    /// <summary>
    /// PageBusinessTouchPanel.xaml 的交互逻辑
    /// </summary>
    public partial class PageBusinessTouchPanel : Page
    {
        #region 分类定义
        /// <summary>
        /// 动态分类菜单
        /// </summary>
        private ObservableCollection<UcMeunPage> obFoodCategory = new ObservableCollection<UcMeunPage>();
        /// <summary>
        /// 加载的分类菜单
        /// </summary>
        private IList<FoodCategory> CategoryList = new List<FoodCategory>();
        /// <summary>
        /// 总分类集合
        /// </summary>
        private IList<FoodCategory> FoodCategoryList = null;
        #endregion
        #region 菜品定义
        /// <summary>
        /// 动态资源菜品
        /// </summary>
        private ObservableCollection<ResourceFood> obResourceFoodList = new ObservableCollection<ResourceFood>();

        /// <summary>
        /// 总资源菜品
        /// </summary>
        private IList<ResourceFood> ResourceFoodList = null;
        /// <summary>
        /// 更新的菜品资源集合
        /// </summary>
        private IList<ResourceFood> ResourceFoodUpdateList = new List<ResourceFood>();
        /// <summary>
        /// 菜品备注
        /// </summary>
        private ObservableCollection<UCFoodMemo> obFoodMemo = new ObservableCollection<UCFoodMemo>();
        /// <summary>
        /// 是否有可用备注
        /// </summary>
        private bool hasResourceMemo = false;
        #endregion
        #region 账单定义
        /// <summary>
        /// 动态订单菜品
        /// </summary>
        private ObservableCollection<BillFood> obBillFoodList = new ObservableCollection<BillFood>();
        /// <summary>
        /// 
        /// </summary>
        private IList<BillFood> BillFoodList = null;
        /// <summary>
        /// 当前订单菜品
        /// </summary>
        public BillFood CurrentBillFood = null;
        /// <summary>
        /// 当前订单
        /// </summary>
        private Bill CurrentBill;
        /// <summary>
        /// 标识加菜但未确认
        /// </summary>
        private bool hasAddFood = false;
        #endregion 

        private ControlHint.DelegateMessageTrigger MessageTrigger = null;       //渐变弹出框的触发器
        private void OnMessageTrigger(string message)       //显示透明渐变提示
        {
            this.HintCenter.Title = message;
            Storyboard story = this.FindResource("story4Hint") as Storyboard;
            if (story != null) story.Begin();
        }

        public PageBusinessTouchPanel()
        {
            InitializeComponent();
        }

        //窗体加载
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //绑定菜品分类数据
            this.listCategory.ItemsSource = obFoodCategory;
            //绑定菜品数据
            this.listResourceFood.ItemsSource = obResourceFoodList;
            //绑定订单菜品
            this.listBillFood.ItemsSource = obBillFoodList;
            this.listBillFood.SelectionChanged += new SelectionChangedEventHandler(listBillFood_SelectionChanged);
            GetAllFoodCategory();
            this.LoadHighMeun();
            this.InitMemo();
            this.InitBill();
        }


        #region  窗体加载的事件

        /// <summary>
        /// 装载总菜单项
        /// </summary>
        private void LoadHighMeun()
        {
            IList<FoodCategory> categorys = new List<FoodCategory>();
            categorys.Add(new FoodCategory() { Title = "菜 品", IsComplexType = false });
            categorys.Add(new FoodCategory() { Title = "套 餐", IsComplexType = true });

            this.HighFoodCategory.ItemsSource = categorys;
            //this.HighFoodCategory
            this.HighFoodCategory.SelectionChanged += new SelectionChangedEventHandler(HighFoodCategory_SelectionChanged);
            this.listResourceFood.SelectionChanged += new SelectionChangedEventHandler(listResourceFood_SelectionChanged);
            if (this.HighFoodCategory.HasItems)
            {
                this.HighFoodCategory.SelectedIndex = 0;
            }
        }
        void HighFoodCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            FoodCategory item=this.HighFoodCategory.SelectedItem as FoodCategory;
            if(item!=null)
            {
                CategoryList = this.FoodCategoryList.Where(c => c.IsComplexType == item.IsComplexType).ToList();
                this.obFoodCategory.Clear();
                this.InnerCategory(CategoryList);
            }
        }

        /// <summary>
        /// 装载一个分类菜品
        /// </summary>
        /// <param name="categoryid">分类ID</param>
        public void InnerDish(int categoryid)
        {
            IList<ResourceFood> CategoryFoods = this.ResourceFoodList.Where(f => f.CategoryId == categoryid).ToList();
            this.obResourceFoodList.Clear();
            foreach (var item in CategoryFoods)
            {
                this.obResourceFoodList.Add(item);
            }

        }
        private void listResourceFood_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ResourceFood currentFood = this.listResourceFood.SelectedItem as ResourceFood;
            this.listResourceFood.SelectedIndex = -1;
            if (currentFood != null)
            {
                this.AddFood(currentFood, 1);
            }
        }

        /// <summary>
        /// 装载一个分类导航
        /// </summary>
        /// <param name="categorys">分类集合</param>
        private void InnerCategory(IList<FoodCategory> categorys)
        {
            if (!categorys.Any())
            {
                this.obResourceFoodList.Clear();
                return;
            }
            UcMeunPage category = new UcMeunPage(categorys);
            category.InnerDishChanged += new UcMeunPage.DelegateInnerDishChanged(this.OnItemControlInnerDishChanged);
            obFoodCategory.Add(category);
        }
        private void OnItemControlInnerDishChanged(FoodCategory category)
        {
            //if (this.InnerDishChanged != null)
            //this.InnerDishChanged(categoryId);
            this.OnDishChanged(category);
        }

        /// <summary>
        /// 响应菜品分类
        /// </summary>
        /// <param name="category"></param>
        private void OnDishChanged(FoodCategory category)
        {
            this.DelCategoryItem(category);
            if (category.CategoryChildren.Any())
            {

                this.InnerCategory(category.CategoryChildren);
                OnDishChanged(category.CategoryChildren.First());
            }
            else
            {
                this.InnerDish(category.Id.Value);
            }
        }

        /// <summary>
        /// 删除菜品分类项
        /// </summary>
        private void DelCategoryItem(FoodCategory category)
        {
            UcMeunPage meunPage = this.obFoodCategory.Last();
            if (meunPage.AllFoodCategory.Contains(category))
            {
                return;
            }
            this.obFoodCategory.Remove(meunPage);
            DelCategoryItem(category);
        }

        /// <summary>
        /// 获取订单选中的菜品
        /// </summary>
        //private void SelectCurrentItem(object sender, MouseButtonEventArgs e)
        //{
        //    ListBoxItem item = (ListBoxItem)sender;
        //    item.IsSelected = true;
        //    this.CurrentBillFood = this.listBillFood.SelectedItem as BillFood;
        //}

        /// <summary>
        /// 获取菜品分类
        /// </summary>
        private void GetAllFoodCategory()
        {
            IList<FoodCategory> AllCategorys = App.MPCRClient.GetAllCategory();
            IList<FoodCategory> parents = AllCategorys.Where(e => e.SearchPath.LastIndexOf('.') == -1).ToList();
            IList<FoodCategory> children = AllCategorys.Where(e => e.SearchPath.LastIndexOf('.') > 0).ToList();
            this.FoodCategoryList = StackFoodCategory(parents, children);
        }

        /// <summary>
        /// 层叠菜品分类
        /// </summary>
        private IList<FoodCategory> StackFoodCategory(IList<FoodCategory> parents, IList<FoodCategory> children)
        {
            IList<FoodCategory> stactkCategory = new List<FoodCategory>();
            foreach (var item in parents)
            {
                List<FoodCategory> itemChildren = children.Where(c => c.ParentId == item.Id).ToList();
                if (itemChildren.Any())
                {
                    itemChildren.ForEach(c => children.Remove(c));
                    item.CategoryChildren = StackFoodCategory(itemChildren, children);
                    stactkCategory.Add(item);
                }
                else
                {
                    stactkCategory.Add(item);
                }
            }
            return stactkCategory;
        }

        private void GetAllFood()
        { }

        #endregion

        /// <summary>
        /// 渐变提示
        /// </summary>
        private void ShowInfo(string message)
        {
            this.MessageTrigger = new ControlHint.DelegateMessageTrigger(this.OnMessageTrigger);        //渐变窗口弹出提示
            this.MessageTrigger(message);
        }

        #region 订单处理

        void listBillFood_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //ListBoxItem item = (ListBoxItem)sender;
            //item.IsSelected = true;
            this.CurrentBillFood = this.listBillFood.SelectedItem as BillFood;
            if (this.CurrentBillFood != null)
            {
                this.listModleMemo.SelectedIndex = -1;
                this.listModleMemo.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 初始化备注信息
        /// </summary>
        private void InitMemo()
        {
            List<String> resourceMemo = new List<string>();
            resourceMemo.Add("口味");
            resourceMemo.Add("做法");
            resourceMemo.Add("加料");
            this.listModleMemo.ItemsSource = resourceMemo;
            this.listModleMemo.SelectionChanged += new SelectionChangedEventHandler(listResourceMemo_SelectionChanged);
            this.listFoodMemo.ItemsSource = this.obFoodMemo;
        }

        void listResourceMemo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string selectMemo = this.listModleMemo.SelectedItem as String;
            if (!string.IsNullOrWhiteSpace(selectMemo))
            {
                this.InnerMemo(this.CurrentBillFood.FoodId.GetValueOrDefault(), selectMemo);
            }
        }

        /// <summary>
        /// 加载菜品备注
        /// </summary>
        /// <param name="foodId"></param>
        private void InnerMemo(int foodId,string memo)
        {
            this.obFoodMemo.Clear();
            ResourceFood resourceFood = App.MPCRClient.GetFood(foodId);
            if (resourceFood == null)
            {
                this.memoPanel.Visibility=Visibility.Collapsed;
                return;
            }
            if (string.IsNullOrWhiteSpace(resourceFood.Approach) && string.IsNullOrWhiteSpace(resourceFood.Taste))
            {
                this.memoPanel.Visibility = Visibility.Collapsed;
                return;
            }
            this.memoPanel.Visibility = Visibility.Visible;
            List<String> listString = new List<string>();
            switch (memo)
            {
                case "口味":
                    {
                        if (!string.IsNullOrWhiteSpace(resourceFood.Taste))
                        {
                            listString = resourceFood.Taste.Split(',').ToList();
                        }
                        break;
                    }
                case "做法":
                    {
                        if (!string.IsNullOrWhiteSpace(resourceFood.Approach))
                        {
                            listString = resourceFood.Approach.Split(',').ToList();
                        }
                        break;
                    }
                case "加料":
                    {break;}
                default:{break;}
            }
            if (listString.Any())
            {
                UCFoodMemo newMemo = new UCFoodMemo(listString);
                newMemo.InnerMemoChanged += new UCFoodMemo.DelegateInnerMemoChanged(newMemo_InnerMemoChanged);
                this.obFoodMemo.Add(newMemo);
            }
        }

        void newMemo_InnerMemoChanged(string selectMemo)
        {
            string selectModle = this.listModleMemo.SelectedItem as String;
            switch (selectModle)
            {
                case "口味":
                    {
                        this.CurrentBillFood.FoodTaste = BillFoodMemoAdd(this.CurrentBillFood.FoodTaste,
                                                                       selectMemo);
                        break;
                    }
                case "做法":
                    {
                        this.CurrentBillFood.FoodCooking = BillFoodMemoAdd(this.CurrentBillFood.FoodCooking, selectMemo);
                        break;
                    }
                case "加料":
                    { break; }
                default: { break; }
            }
        }

        /// <summary>
        /// 清除菜品备注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void memoRemove_Click(object sender, RoutedEventArgs e)
        {
            #region //逐个删除菜品备注
            //string selectModle = this.listModleMemo.SelectedItem as String;
            //switch (selectModle)
            //{
            //    case "口味":
            //        {
            //            if (!string.IsNullOrWhiteSpace(this.CurrentBillFood.FoodTaste))
            //            {
            //                this.CurrentBillFood.FoodTaste = BillFoodMemoDel(this.CurrentBillFood.FoodTaste);                            
            //            }
            //            break;
            //        }
            //    case "做法":
            //        {
            //            if (!string.IsNullOrWhiteSpace(this.CurrentBillFood.FoodCooking))
            //            {
            //                this.CurrentBillFood.FoodCooking = BillFoodMemoDel(this.CurrentBillFood.FoodCooking);
            //            }
            //            break;
            //        }
            //    case "加料":
            //        { break; }
            //    default: { break; }
            //}
            #endregion
            //清除口味
            if (!string.IsNullOrWhiteSpace(this.CurrentBillFood.FoodTaste))
            {
                this.CurrentBillFood.FoodTaste = null;
            }
            //清除做法
            if (!string.IsNullOrWhiteSpace(this.CurrentBillFood.FoodCooking))
            {
                this.CurrentBillFood.FoodCooking = null;
            }
        }

        /// <summary>
        /// 设置菜品备注
        /// </summary>
        private string BillFoodMemoAdd(string localMemo, string memo)
        {
            if(string.IsNullOrWhiteSpace(localMemo))
            {
                return memo;
            }
            else
            {
                return string.Format("{0},{1}", localMemo, memo);
            }
        }
        /// <summary>
        /// 清除菜品备注
        /// </summary>
        private string BillFoodMemoDel(string localMemo)
        {
            if (localMemo == null)
            {
                return null;
            }
            List<String> memoList = null;
            string memoString = null;
            memoList = localMemo.Split(',').ToList();
            if (memoList.Any())
            {
                memoList.Remove(memoList.Last());

                foreach (var memo in memoList)
                {
                    memoString = this.BillFoodMemoAdd(memoString, memo);
                }
            }
            return memoString;
        }


        /// <summary>
        /// 初始化账单
        /// </summary>
        private void InitBill()
        {
            this.CurrentBill = new Bill() {Id = 0, State = Bill.STATE_OPENED};
            this.textTotalPrice.Text = "暂无账单";
            this.hasAddFood = false;
            this.obBillFoodList.Clear();
            ResourceFoodList = App.MPCRClient.GetAllFoods();
        }
        /// <summary>
        /// 菜品总价
        /// </summary>
        private float totalPrice = 0;
        /// <summary>
        /// 计算账单总额
        /// </summary>
        private float calculateTotalPrice()
        {
            totalPrice = 0;
            foreach (BillFood billFood in this.obBillFoodList)
            {
                totalPrice += billFood.FoodPrice.Value * billFood.FoodNumber.Value;
            }
            if ((float)((int)totalPrice) == totalPrice)
            {
                this.textTotalPrice.Text = string.Format("金额：{0}元", totalPrice.ToString());
            }
            else
            {
                this.textTotalPrice.Text = string.Format("金额：{0}元", totalPrice.ToString("F1"));
            }
            return totalPrice;
        }
        /// <summary>
        /// 是否是更新菜品
        /// </summary>
        bool isUpdateFood = false;
        private void AddFood(ResourceFood food,float number)
        {
            //估清判断
            if (ApplicationSetting.ResourceFoodCategories != null)
            {
                if (ApplicationSetting.ResourceFoodCategories.Contains(food))
                {
                    this.MessageTrigger = new ControlHint.DelegateMessageTrigger(this.OnMessageTrigger);        //渐变窗口弹出提示
                    if (food.HasSoldout == true)
                    {
                        this.MessageTrigger(string.Format("{0}已估清!", food.Title));
                        return;
                    }
                    if (food.RemainNumber == 0)
                    {
                        this.MessageTrigger(string.Format("{0}已售完!", food.Title));
                        return;
                    }
                    isUpdateFood = true;
                }
                else
                {
                    isUpdateFood = false;
                }
            }
            var defaultState = BillFoodStateContext.GetName(BillFoodState.Default);
            bool has = false;
            BillFood billFood = null;
            if (this.obBillFoodList.Any())
            {
                IList<BillFood> BillFoodList = this.obBillFoodList.Where(e => e.FoodId == food.Id && e.State == defaultState).ToList();
                if (BillFoodList.Any())
                {
                    has = true;
                    billFood = BillFoodList.FirstOrDefault();
                    billFood.FoodNumber += number;
                }
            }
            if (!has)
            {
                DateTime nowTime = DateTime.Now;
                billFood = new BillFood
                {
                    IsRealTimePrice = food.IsRealTimePrice,
                    SearchPath = food.SearchPath,
                    State = defaultState,

                    // 注释原因：集团现在移除了SN,需改为使用ID关联。Mark By Tom20121013
                    //SerialNumber = food.SerialNumber,

                    FoodId = food.Id,
                    FoodNumber = number,
                    //FoodCooking = food.Approach,
                    //FoodTaste =food.Taste,
                    FoodPrice = food.Price,
                    FoodTitle = food.Title,
                    FoodUnit = food.Unit,
                    HasCookdirectly = food.HasCookdirectly,
                    BillId = this.CurrentBill.Id,
                    CategoryId = food.CategoryId,
                    //StartTime = food.StartTime,
                    //EndTime = food.EndTime,
                    StartTime = nowTime,
                    PayStyle = food.PayStyle,
                    IsComplexDish = food.IsComplexDish,
                    EmployeeId = ApplicationSetting.Employee.Id,
                    OriginalPrice = food.Price.GetValueOrDefault()
                };
                this.obBillFoodList.Add(billFood);
            }

            if (isUpdateFood)
            {
                food.RemainNumber -= (int)number;
                food.Version = (int)number;
                ResourceFoodUpdateList.Add(food);
            }
            this.hasAddFood = true;
            //选中操作的订单菜品
            this.listBillFood.SelectedItem = billFood;
            this.CurrentBillFood = billFood;
            //移动滚动条到最后添加的菜品上
            //this.listBillFood.Items.MoveCurrentToLast();
            this.listBillFood.ScrollIntoView(this.listBillFood.SelectedItem); 
            this.calculateTotalPrice();
        }

        /// <summary>
        /// 删除订单菜品
        /// </summary>
        private void RemoveFood(BillFood foodSubtract, float number)
        {

            if (this.CurrentBill == null || this.CurrentBill.State == Bill.STATE_COMPLETED || this.CurrentBill.State == Bill.STATE_ABORTED) return;
            if (foodSubtract == null) return;
            if (!BusinessHelper.CheckPaying(this.CurrentBill))
            {
                return;
            }
            var d = BillFoodStateContext.GetName(BillFoodState.Default);
            var p = BillFoodStateContext.GetName(BillFoodState.Prepared);
            var c = BillFoodStateContext.GetName(BillFoodState.Cooked);
            if (foodSubtract.State == d)//加菜未确认的则直接从列表中移除
            {
                float maxNumber = foodSubtract.FoodNumber ?? 0F;
                if (number > maxNumber)
                {
                    throw new Exception("退菜数量超出范围!");
                }
                foodSubtract.FoodNumber -= number;

                // 修改原因：满足新需求，数量可以是小数，保留2位。Update By Tom20121015
                if (foodSubtract.FoodNumber == 0)
                {
                    int index = this.listBillFood.SelectedIndex;
                    this.obBillFoodList.Remove(foodSubtract);
                    this.SelectNext(index);
                }
            }
            else 
            {
                this.TouchRemoveFood(foodSubtract);      //退菜
            }

            this.calculateTotalPrice();

        }

        /// <summary>
        /// 退菜请求
        /// </summary>
        /// <param name="abortFood"></param>
        private void TouchRemoveFood(BillFood abortFood)
        {
            try
            {
                var emp = BusinessHelper.GetCanRetreatDishEmployee();
                if (emp == null) return;

                float totalNumber = BusinessHelper.CalcFoodNumber(abortFood, this.obBillFoodList.ToList());
                DialogRemoveFood dialog = new DialogRemoveFood(abortFood, totalNumber);
                dialog.Owner = Application.Current.MainWindow;
                dialog.ShowDialog();
                if (!dialog.isOK) return;

                // 修改原因：满足新需求，数量可以是小数，保留2位。Update By Tom20121015
                //if (dialog.FoodNumber <= 0 || dialog.FoodNumber > totalNumber)
                if (dialog.FoodNumber <= 0F || dialog.FoodNumber > totalNumber)
                {
                    throw new Exception("退菜数量超出范围。");
                }

                abortFood = BusinessHelper.BillFoodRemove(abortFood, dialog.FoodNumber, emp.Id.GetValueOrDefault(), dialog.Reason);
                if (abortFood != null)
                {
                    this.obBillFoodList.Add(abortFood);
                }
                
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }

        }


        /// <summary>
        /// 选中下一个订单菜品
        /// </summary>
        private void SelectNext(int currentIndex)
        {
            if (this.obBillFoodList.Any())
            {
                int maxcount = this.obBillFoodList.Count;
                int newIndex = currentIndex;
                if (newIndex >= maxcount)
                {
                    newIndex = currentIndex - 1;
                    if (newIndex < 0)
                    {
                        return;
                    }
                }
                this.listBillFood.SelectedIndex = newIndex;
                
            }
        }

        #endregion 

        #region 挂单操作
        private Dictionary<int, IList<BillFood>> RestBillFood = new Dictionary<int, IList<BillFood>>();

        /// <summary>
        /// 装载挂单
        /// </summary>
        private void RestBillMethod(int key)
        {
            List<BillFood> billFoods = null;
            if (RestBillFood.ContainsKey(key))
            {
                if (this.obBillFoodList.Any())
                {
                    if (MessageBoxResult.Cancel == MessageBox.Show("新账单未结账，是否装载?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                    {
                        return;
                    }
                }
                billFoods = RestBillFood[key].ToList();
                this.RestBillFood.Remove(key);
                if (key == 1)
                {
                    this.text_rest1.Text = "挂单1";
                }
                else
                {
                    this.text_rest2.Text = "挂单2";
                }
                this.obBillFoodList.Clear();
                billFoods.ForEach(f => this.obBillFoodList.Add(f));
                this.calculateTotalPrice();
            }
            else
            {
                if (this.obBillFoodList.Any())
                {
                    billFoods = this.obBillFoodList.ToList();
                    RestBillFood.Add(key, billFoods);
                    if (key == 1)
                    {
                        this.text_rest1.Text = "已挂单";
                    }
                    else
                    {
                        this.text_rest2.Text = "已挂单";
                    }
                    this.InitBill();
                }
            }
        }

        private void Rest1_Click(object sender, RoutedEventArgs e)
        {
            this.RestBillMethod(1);
        }

        private void Rest2_Click(object sender, RoutedEventArgs e)
        {
            this.RestBillMethod(2);
        }
        #endregion

        #region 清台
        /// <summary>
        /// 清台
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bill_Abort_Click(object sender, RoutedEventArgs e)
        {
            if (this.CurrentBill.Id > 0)
            {
                BusinessHelper.BillAbort(this.CurrentBill);
            }
            this.InitBill();
        }

        #endregion 

        /// <summary>
        /// - 操作
        /// </summary>
        private void BillFood_Sub_Click(object sender, RoutedEventArgs e)
        {
            this.RemoveFood(this.CurrentBillFood, 1);
        }

        /// <summary>
        /// +  操作
        /// </summary>
        private void BillFood_Add_Click(object sender, RoutedEventArgs e)
        {
            ResourceFood addResourceFood = App.MPCRClient.GetFood(this.CurrentBillFood.FoodId.GetValueOrDefault());
            if (addResourceFood != null)
            {
                this.AddFood(addResourceFood,1);
            }
        }

        private void innerFrame_ContentRendered(object sender, EventArgs e)
        {
            Page p = (this.innerFrame.Content as Page);
            if (p == null)
            {
                return;
            }
            p.Focusable = true;
            p.Focus();
        }

        /// <summary>
        /// 送单
        /// </summary>
        private void Bill_Send_Click(object sender, RoutedEventArgs e)
        {
            this.BillSend();
        }

        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bill_Completed_Click(object sender, RoutedEventArgs e)
        {
            this.BillSend();
            var foodResourcePanel = new BillCompletedPanel();
            this.innerFrame.Content = foodResourcePanel;
        }

        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Bill_Back_Click(object sender, RoutedEventArgs e)
        {
            if (this.innerFrame.Content != null)
            {
                this.innerFrame.Content = null;
                return;
            }
            //Environment.Exit(0);
            
        }

        /// <summary>
        /// 上翻
        /// </summary>
        private void Bill_Perw_Click(object sender, RoutedEventArgs e)
        {
            this.BillScrollMethod(true);
        }

        /// <summary>
        /// 下翻
        /// </summary>
        private void Bill_Next_Click(object sender, RoutedEventArgs e)
        {
            this.BillScrollMethod(false);
        }

        private void BillScrollEnabled()
        {
            double billWidth = listBillFood.ActualWidth;
            double billHeight = listBillFood.ActualHeight;
        }

        /// <summary>
        ///  订单菜品滚动方法
        /// </summary>
        private void BillScrollMethod(bool scrollUp)
        {
            int index = this.listBillFood.SelectedIndex;
            if (index < 0)
            {
                return;
            }
            int nextIndex = 0;
            BillFood nextBill = null;
            if (scrollUp)
            {
                nextIndex = index - 1;
                if (nextIndex < 0)
                {
                    nextIndex = this.obBillFoodList.IndexOf(this.obBillFoodList.Last());
                }
            }
            else
            {
                int maxCount = this.obBillFoodList.Count;
                nextIndex = index + 1;
                if (nextIndex >= maxCount)
                {
                    nextIndex = 0;
                }
            }
            nextBill = this.obBillFoodList.ElementAt(nextIndex);
            this.listBillFood.SelectedItem = nextBill;
            this.listBillFood.ScrollIntoView(nextBill);
        }

        private Timer scrollTime = null;
        private bool scrollState = false;
        private void ScrollTimer()
        {
            scrollTime = new Timer();
            scrollTime.Interval = 1;

            scrollTime.Elapsed += new ElapsedEventHandler(scrollTime_Elapsed);
            scrollTime.Start();
        }

        void scrollTime_Elapsed(object sender, ElapsedEventArgs e)
        {
            BillScrollMethod(scrollState);
        }

        /// <summary>
        /// 送单
        /// </summary>
        private void BillSend()
        {
            try
            {
                if (this.hasAddFood)
                {
                    //生成账单号
                    if (this.CurrentBill.Id == 0)
                    {
                        ResourceSpace FastSpace = new ResourceSpace() {Id = 0, Title = "快餐", MaxNumber = 1, Memo = null};
                        this.CurrentBill = BusinessHelper.OpenSpace(FastSpace);
                    }
                    BusinessHelper.BillFoodAdd(this.obBillFoodList.ToList(), this.CurrentBill.Id.GetValueOrDefault());
                    //更新装载账单菜品
                    this.obBillFoodList.Clear();
                    List<BillFood> billFoods = App.MPCRClient.GetBillFoods(this.CurrentBill.Id.GetValueOrDefault());
                    if (billFoods.Any())
                    {
                        billFoods.ForEach(b => this.obBillFoodList.Add(b));
                    }
                    this.hasAddFood = false;

                    if (this.CurrentBill.State == Bill.STATE_REQUIRED)
                    {
                        return;
                    }
                    this.CurrentBill = BusinessHelper.ChangeTableStatus(this.CurrentBill, Bill.STATE_REQUIRED);
                    ApplicationSetting.RefreshSpaces();
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }


        //private void Bill_Prew_MouseDown(object sender, MouseButtonEventArgs e)
        //{
        //    scrollState = true;
        //    this.scrollTime.Enabled = true;
        //}

        //private void Bill_Prew_MouseUp(object sender, MouseButtonEventArgs e)
        //{
        //    this.scrollTime.Enabled = false;
        //}

    }
}
